package service

import (
	"context"
	"forum/app/user/internal/repository/db/dao"
	pb "forum/idl/pb/user"
	"forum/pkg/e"
	"sync"
)

var UserSrvIns *UserSrv
var UserSrvOnce sync.Once

type UserSrv struct {
	pb.UnimplementedUserServiceServer
}

func GetUserSrv() *UserSrv {
	UserSrvOnce.Do(func() {
		UserSrvIns = &UserSrv{}
	})
	return UserSrvIns
}

func (u *UserSrv) UserLogin(ctx context.Context, req *pb.UserRequest) (resp *pb.UserDetailResponse, err error) {
	resp = new(pb.UserDetailResponse)
	resp.Code = e.SUCCESS
	r, err := dao.NewUserDao(ctx).GetUserInfo(req)
	if err != nil {
		resp.Code = e.ERROR
		return
	}
	if r.CheckPassword(req.Password) == false {
		resp.Code = e.ErrorPassword
		return
	}
	resp.UserDetail = &pb.UserResponse{
		UserId:   uint64(r.ID),
		NickName: r.Nickname,
		UserName: r.Username,
	}
	return
}

func (u *UserSrv) UserRegister(ctx context.Context, req *pb.UserRequest) (resp *pb.UserCommonResponse, err error) {
	resp = new(pb.UserCommonResponse)
	resp.Code = e.SUCCESS
	err = dao.NewUserDao(ctx).CreateUser(req)
	if err != nil {
		resp.Code = e.ERROR
		return
	}
	return
}

func (u *UserSrv) UserLogout(ctx context.Context, req *pb.UserRequest) (resp *pb.UserCommonResponse, err error) {
	return
}

func (u *UserSrv) UserUpdate(ctx context.Context, req *pb.UserRequest) (resp *pb.UserCommonResponse, err error) {
	resp = new(pb.UserCommonResponse)
	resp.Code = e.SUCCESS
	userDao := dao.NewUserDao(ctx)

	// 确认用户存在
	r, err := userDao.GetUserInfo(req)
	if err != nil {
		resp.Code = e.UserNotFound
		return
	}

	// username不允许修改
	if r.Username != req.UserName {
		resp.Code = e.ErrorUserUpdate
		return
	}

	// 更新用户信息
	err = userDao.UpdateUser(req)
	if err != nil {
		resp.Code = e.ERROR
		return
	}

	return
}

func (u *UserSrv) UserDelete(ctx context.Context, req *pb.UserRequest) (resp *pb.UserCommonResponse, err error) {
	resp = new(pb.UserCommonResponse)
	resp.Code = e.SUCCESS
	err = dao.NewUserDao(ctx).DeleteUser(req)
	if err != nil {
		resp.Code = e.ERROR
		return
	}
	return
}
